#include "knowledgebase.h"
#include "rule.h"
#include <QStringList>
#include "knowledgebase.h"

KnowledgeBase::KnowledgeBase(QObject *parent)
    : QObject(parent)
{
    initializeRules();
}

void KnowledgeBase::initializeRules()
{
    // 清空现有规则
    m_rules.clear();
    m_ruleCategories.clear();
    
    // 初始化空规则列表，等待从文件加载
    m_selectedCategories = QStringList();
}

QList<Rule> KnowledgeBase::getAnimalRules() const
{
    return m_rules;
}

QStringList KnowledgeBase::getRuleCategories() const
{
    return m_ruleCategories.keys();
}

QList<Rule> KnowledgeBase::getRulesByCategory(const QString &category) const
{
    if (m_ruleCategories.contains(category)) {
        return m_ruleCategories.value(category);
    }
    return QList<Rule>();
}

void KnowledgeBase::selectRules(const QStringList &selectedCategories)
{
    m_selectedCategories = selectedCategories;
    
    // 根据选择的类别重新构建规则列表
    m_rules.clear();
    for (const QString &category : m_selectedCategories) {
        if (m_ruleCategories.contains(category)) {
            m_rules.append(m_ruleCategories.value(category));
        }
    }
    
    // 始终包含自定义规则
    if (m_ruleCategories.contains("自定义规则")) {
        m_rules.append(m_ruleCategories.value("自定义规则"));
    }
}

QList<Rule> KnowledgeBase::getSelectedRules() const
{
    return m_rules;
}

void KnowledgeBase::addCustomRule(const Rule &rule, const QString &category)
{
    // 如果类别不存在，创建一个新的类别
    if (!m_ruleCategories.contains(category)) {
        m_ruleCategories[category] = QList<Rule>();
    }
    
    // 添加规则到类别
    m_ruleCategories[category].append(rule);
    
    // 如果类别已被选中，也添加到主规则列表
    if (m_selectedCategories.contains(category) || category == "自定义规则") {
        m_rules.append(rule);
    }
}